package ren.kane.phoenix.util.io;

import java.io.IOException;
import java.io.PipedOutputStream;

/**
 * @author renrk(1275) on 2019-07-30 3:56 PM
 **/
public class Sender extends Thread {
    // 管道输出流对象，它和“管道输入流(PipedInputStream)”对象绑定，从而可以将数据发送给“管道输入流”的数据，然后用户可以从“管道输入流”读取数据
    private PipedOutputStream pipedOutputStream = new PipedOutputStream();

    public PipedOutputStream getPipedOutputStream() {
        return pipedOutputStream;
    }

    @Override
    public void run() {
        // writeShortMessage();
        writeLongMessage();
    }

    // 向“管道输出流”中写入一则较简短的消息："this is a short message"
    private void writeShortMessage() {
        String strInfo = "this is a short message";
        try {
            pipedOutputStream.write(strInfo.getBytes());
            pipedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 向“管道输出流”中写入一则较长的消息
    private void writeLongMessage() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 102; i++) {
            sb.append("0123456789");
        }
        sb.append("abcdefghijklmnopqrstuvwxyz");
        // str的总长度是1020+26=1046个字节
        String str = sb.toString();
        try {
            pipedOutputStream.write(str.getBytes());
            pipedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
